import type { Resume, ResumeTemplate, Theme } from '../types/index';

// IndexDB数据库名称和版本
const DB_NAME = 'resumeDB';
const DB_VERSION = 1;

// 存储对象名称
const STORES = {
  RESUMES: 'resumes',
  TEMPLATES: 'templates',
  THEMES: 'themes'
};

// 打开数据库连接
const openDB = (): Promise<IDBDatabase> => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION);
    
    // 数据库升级事件
    request.onupgradeneeded = (event) => {
      const db = (event.target as IDBOpenDBRequest).result;
      
      // 创建简历存储
      if (!db.objectStoreNames.contains(STORES.RESUMES)) {
        db.createObjectStore(STORES.RESUMES, { keyPath: 'id' });
      }
      
      // 创建模板存储
      if (!db.objectStoreNames.contains(STORES.TEMPLATES)) {
        db.createObjectStore(STORES.TEMPLATES, { keyPath: 'id' });
      }
      
      // 创建主题存储
      if (!db.objectStoreNames.contains(STORES.THEMES)) {
        db.createObjectStore(STORES.THEMES, { keyPath: 'id' });
      }
    };
    
    request.onsuccess = (event) => {
      resolve((event.target as IDBOpenDBRequest).result);
    };
    
    request.onerror = (event) => {
      reject((event.target as IDBOpenDBRequest).error);
    };
  });
};

// 通用的数据库操作函数
const dbOperation = async <T>(storeName: string, mode: IDBTransactionMode, operation: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> => {
  const db = await openDB();
  return new Promise((resolve, reject) => {
    const transaction = db.transaction(storeName, mode);
    const store = transaction.objectStore(storeName);
    const request = operation(store);
    
    request.onsuccess = () => {
      resolve(request.result);
    };
    
    request.onerror = () => {
      reject(request.error);
    };
    
    transaction.oncomplete = () => {
      db.close();
    };
  });
};

// 简历相关操作
export const resumeService = {
  // 获取所有简历
  getAllResumes: async (): Promise<Resume[]> => {
    return dbOperation<Resume[]>(STORES.RESUMES, 'readonly', (store) => store.getAll());
  },
  
  // 获取单个简历
  getResume: async (id: string): Promise<Resume | undefined> => {
    return dbOperation<Resume | undefined>(STORES.RESUMES, 'readonly', (store) => store.get(id));
  },
  
  // 创建或更新简历
  saveResume: async (resume: Resume): Promise<string> => {
    await dbOperation(STORES.RESUMES, 'readwrite', (store) => store.put(resume));
    return resume.id;
  },
  
  // 删除简历
  deleteResume: async (id: string): Promise<void> => {
    await dbOperation(STORES.RESUMES, 'readwrite', (store) => store.delete(id));
  }
};

// 模板相关操作
export const templateService = {
  // 获取所有模板
  getAllTemplates: async (): Promise<ResumeTemplate[]> => {
    return dbOperation<ResumeTemplate[]>(STORES.TEMPLATES, 'readonly', (store) => store.getAll());
  },
  
  // 获取单个模板
  getTemplate: async (id: string): Promise<ResumeTemplate | undefined> => {
    return dbOperation<ResumeTemplate | undefined>(STORES.TEMPLATES, 'readonly', (store) => store.get(id));
  },
  
  // 初始化默认模板
  initDefaultTemplates: async (templates: ResumeTemplate[]): Promise<void> => {
    const db = await openDB();
    const transaction = db.transaction(STORES.TEMPLATES, 'readwrite');
    const store = transaction.objectStore(STORES.TEMPLATES);
    
    return new Promise((resolve, reject) => {
      templates.forEach(template => {
        store.put(template);
      });
      
      transaction.oncomplete = () => {
        db.close();
        resolve();
      };
      
      transaction.onerror = () => {
        reject(transaction.error);
      };
    });
  }
};

// 主题相关操作
export const themeService = {
  // 获取所有主题
  getAllThemes: async (): Promise<Theme[]> => {
    return dbOperation<Theme[]>(STORES.THEMES, 'readonly', (store) => store.getAll());
  },
  
  // 获取单个主题
  getTheme: async (id: string): Promise<Theme | undefined> => {
    return dbOperation<Theme | undefined>(STORES.THEMES, 'readonly', (store) => store.get(id));
  },
  
  // 初始化默认主题
  initDefaultThemes: async (themes: Theme[]): Promise<void> => {
    const db = await openDB();
    const transaction = db.transaction(STORES.THEMES, 'readwrite');
    const store = transaction.objectStore(STORES.THEMES);
    
    return new Promise((resolve, reject) => {
      themes.forEach(theme => {
        store.put(theme);
      });
      
      transaction.oncomplete = () => {
        db.close();
        resolve();
      };
      
      transaction.onerror = () => {
        reject(transaction.error);
      };
    });
  }
};